//
//  MyNowAddressVC.m
//  JinFuThree
//
//  Created by 毛韶谦 on 2018/9/3.
//  Copyright © 2018年 毛韶谦. All rights reserved.
//

#import "MyNowAddressVC.h"
#import "MSQTextField.h"
#import "SelectAddressTool.h"
#import "SelectAddressTool.h"
#import "MyInfoModel.h"
#import "MyRequestTools.h"

@interface MyNowAddressVC ()<SelectAddressDelegate>

@property (nonatomic, strong) UILabel *headerLabel;
@property (nonatomic, strong) UILabel *nowAddressLabel;
@property (nonatomic, strong) MSQTextField *nowInfoAddressTF;
@property (nonatomic, strong) UIButton *tiJiaoBtn;

@property (nonatomic, strong) MyInfoAddressModel *addressModel;

@property (nonatomic, strong) NSString *provinceCode;
@property (nonatomic, strong) NSString *cityCode;
@property (nonatomic, strong) NSString *districtCode;

@end

@implementation MyNowAddressVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    [self initNavigationBar];
    [self initUI];
    // Do any additional setup after loading the view.
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self updateData];
}

- (void)initNavigationBar {
    
    self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    
    UIView *backgroundView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 60, 44)];
    
    UIButton *button1 = [UIButton buttonWithType:UIButtonTypeSystem];
    [button1 setImage:[[UIImage imageNamed:@"BackArrow"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    button1.frame = CGRectMake(0, 2.5, 30, 41.5f);
    [button1 addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    
    [backgroundView addSubview:button1];
    
    UIButton *button2 = [UIButton buttonWithType:UIButtonTypeSystem];
    [button2 setImage:[[UIImage imageNamed:@"nav_close"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    button2.frame = CGRectMake(30, 2.5, 30, 41.5f);
    [button2 addTarget:self action:@selector(backRootAction) forControlEvents:UIControlEventTouchUpInside];
    
    [backgroundView addSubview:button2];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backgroundView];
}
- (void)backAction {
    
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)backRootAction {
    
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (void)initUI {
    
    self.view.backgroundColor = ListMaoBackgroundColor;
    self.title = @"现居地址";
    
    UIView *whiteView = [[UIView alloc] init];
    whiteView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:whiteView];
    [whiteView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.left.mas_equalTo(self.view);
        make.height.mas_equalTo(110);
        make.top.mas_equalTo(self.headerLabel.mas_bottom);
    }];
    
    UIView *topView = [[UIView alloc] init];
    UITapGestureRecognizer *gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickNowAddressAction)];
    [topView addGestureRecognizer:gesture];
    [whiteView addSubview:topView];
    [topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.mas_equalTo(whiteView);
        make.height.mas_equalTo(55);
    }];
    
    UIView *bottomView = [[UIView alloc] init];
    [whiteView addSubview:bottomView];
    [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.mas_equalTo(whiteView);
        make.height.mas_equalTo(55);
    }];
    
    UIImageView *lineImageView = [[UIImageView alloc] init];
    lineImageView.backgroundColor = ThemeMaoLineColor;
    [whiteView addSubview:lineImageView];
    [lineImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(0.7f);
        make.left.mas_equalTo(whiteView.mas_left).offset(15);
        make.right.mas_equalTo(whiteView.mas_right).offset(-15);
        make.top.mas_equalTo(whiteView.mas_top).offset(54.5f);
    }];
    
    UILabel *leftTopLabel = [[UILabel alloc] init];
    leftTopLabel.text = @"现住省市区";
    leftTopLabel.textColor = HexColor(0x333333);
    leftTopLabel.font = [UIFont systemFontOfSize:14];
    [topView addSubview:leftTopLabel];
    [leftTopLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(topView.mas_left).offset(20);
        make.centerY.mas_equalTo(topView);
        make.width.mas_equalTo(75);
    }];
    UILabel *leftBottomLabel = [[UILabel alloc] init];
    leftBottomLabel.text = @"详细住址";
    leftBottomLabel.textColor = HexColor(0x333333);
    leftBottomLabel.font = [UIFont systemFontOfSize:14];
    [bottomView addSubview:leftBottomLabel];
    [leftBottomLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(bottomView.mas_left).offset(20);
        make.centerY.mas_equalTo(bottomView);
        make.width.mas_equalTo(75);
    }];
    
    
    UIImageView *rightTopImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"ic_chevron_right"]];
    [rightTopImageView setContentMode:UIViewContentModeScaleAspectFit];
    [topView addSubview:rightTopImageView];
    [rightTopImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(topView);
        make.right.mas_equalTo(topView.mas_right).offset(-15);
        make.size.mas_equalTo(CGSizeMake(18, 18));
    }];
    
    self.nowAddressLabel = [[UILabel alloc] init];
    [topView addSubview:self.nowAddressLabel];
    self.nowAddressLabel.text = @"请选择";
    self.nowAddressLabel.textColor = HexColor(0xAAAAAA);
    self.nowAddressLabel.font = [UIFont systemFontOfSize:14];
    [self.nowAddressLabel setTextAlignment:NSTextAlignmentRight];
    [self.nowAddressLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(rightTopImageView.mas_left).offset(-4);
        make.top.bottom.mas_equalTo(topView);
        make.left.mas_equalTo(leftTopLabel.mas_right);
    }];
    
    
    self.nowInfoAddressTF = [[MSQTextField alloc] init];
    [bottomView addSubview:self.nowInfoAddressTF];
    
    self.nowInfoAddressTF.placeholder = @"如长安街666号1栋5层504";
    
    NSMutableAttributedString *placeholder = [[NSMutableAttributedString alloc] initWithString:self.nowInfoAddressTF.placeholder];
    [placeholder addAttribute:NSForegroundColorAttributeName
                        value:HexColor(0xAAAAAA)
                        range:NSMakeRange(0, self.nowInfoAddressTF.placeholder.length)];
    self.nowInfoAddressTF.attributedPlaceholder = placeholder;
    
    [self.nowInfoAddressTF addTarget:self action:@selector(textFieldValueChanged:) forControlEvents:UIControlEventEditingChanged];
    
    self.nowInfoAddressTF.font = [UIFont systemFontOfSize:14];
    self.nowInfoAddressTF.textColor = HexColor(0x333333);
    [self.nowInfoAddressTF setTextAlignment:NSTextAlignmentRight];
    [self.nowInfoAddressTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(leftBottomLabel.mas_right).offset(4);
        make.right.mas_equalTo(bottomView.mas_right).offset(-37);
        make.top.bottom.mas_equalTo(bottomView);
    }];
    
    
    [self.tiJiaoBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.view.mas_left).offset(20);
        make.right.mas_equalTo(self.view.mas_right).offset(-20);
        make.top.mas_equalTo(whiteView.mas_bottom).offset(30);
        make.height.mas_equalTo(45);
    }];
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    gradientLayer.colors = @[(__bridge id)HexColor(0xD6C096).CGColor, (__bridge id)HexColor(0xBEA471).CGColor];
    gradientLayer.locations = @[@0, @1];
    gradientLayer.startPoint = CGPointMake(0, 1);
    gradientLayer.endPoint = CGPointMake(1, 1);
    gradientLayer.frame = CGRectMake(0, 0, ScreenWidthMao - 40, 45);
    gradientLayer.cornerRadius = 4;
    gradientLayer.masksToBounds = YES;
    [self.tiJiaoBtn.layer addSublayer:gradientLayer];
    
    UILabel *label = [[UILabel alloc] init];
    label.font = [UIFont systemFontOfSize:15];
    label.textColor = [UIColor whiteColor];
    label.text = @"提 交";
    [_tiJiaoBtn addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.centerY.mas_equalTo(self.tiJiaoBtn);
    }];
}


- (void)updateData {
    
    [HFQIndicationView showInView:self.view];
    [MyRequestTools MyInfoGetNowAddressWithParameters:nil Success:^(id  _Nullable responseObject) {
        [HFQIndicationView dismiss];
        NSDictionary *dataDic = responseObject[@"data"];
        [self.addressModel setValuesForKeysWithDictionary:dataDic];
        self.nowAddressLabel.text = [NSString stringWithFormat:@"%@%@%@", self.addressModel.livingProvinceVal, self.addressModel.livingCityVal, self.addressModel.livingDistrictVal];
        self.provinceCode = self.addressModel.livingProvince;
        self.cityCode = self.addressModel.livingCity;
        self.districtCode = self.addressModel.livingDistrict;
        
        self.nowInfoAddressTF.text = self.addressModel.livingAddress;
        self.nowAddressLabel.textColor = HexColor(0x333333);
        
        if ([self cheakData]) {
            self.tiJiaoBtn.alpha = 1;
            self.tiJiaoBtn.userInteractionEnabled = YES;
        }else {
            self.tiJiaoBtn.alpha = 0.5;
            self.tiJiaoBtn.userInteractionEnabled = NO;
        }
        
    } Failure:^(id  _Nullable responseObject, NSError * _Nullable error) {
        [HFQIndicationView dismiss];
        
    }];
}


- (void)clickNowAddressAction {
    
    NSArray *tempArr = [AD_UserDefaults objectForKey:ASJF_Area];
    if (!tempArr) {
        
        [ASJF_Service getAreaData];
        [HUD_Mao showCharacterMessage:@"省市区数据请求失败，请重试"];
    }else {
        [self showSelectAddressView];
    }
}


- (void)tiJiaoBtnAction {
    
    if ([self cheakData]) {
        
        NSMutableDictionary *mutDic = [NSMutableDictionary dictionary];
        
        [mutDic setObject:self.provinceCode forKey:@"livingProvince"];
        [mutDic setObject:self.cityCode forKey:@"livingCity"];
        [mutDic setObject:self.districtCode forKey:@"livingDistrict"];
        [mutDic setObject:self.nowInfoAddressTF.text forKey:@"livingAddress"];
        
        [HFQIndicationView showInView:self.view];
        [MyRequestTools MyInfoNowAddressWithParameters:mutDic Success:^(id  _Nullable responseObject) {
            [HFQIndicationView dismiss];
            
            [self backAction];
            
        } Failure:^(id  _Nullable responseObject, NSError * _Nullable error) {
            [HFQIndicationView dismiss];
            
        }];
    }
}

- (void)textFieldValueChanged:(UITextField *)textField {
    
    if ([self cheakData]) {
        self.tiJiaoBtn.alpha = 1;
        self.tiJiaoBtn.userInteractionEnabled = YES;
    }else {
        self.tiJiaoBtn.alpha = 0.5;
        self.tiJiaoBtn.userInteractionEnabled = NO;
    }
}

- (BOOL)cheakData {
    
    if (!self.provinceCode.length) {
        
        return NO;
    }else if (!self.cityCode.length) {
        
        return NO;
    }else if (!self.districtCode.length) {
        
        return NO;
    }else if (!self.nowInfoAddressTF.text.length) {
        
        return NO;
    }
    return YES;
}


-(void)showSelectAddressView {
    
    UIView *backgroundView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidthMao, ScreenHeight)];
    backgroundView.backgroundColor = [UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:0.4/1.0];
    
    UIView *cancleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidthMao, ScreenHeight - 400)];
    cancleView.backgroundColor = [UIColor clearColor];
    [backgroundView addSubview:cancleView];
    
    UIView *whiteView = [[UIView alloc] initWithFrame:CGRectMake(0, ScreenHeight - 400, ScreenHeight, 400)];
    whiteView.backgroundColor = [UIColor whiteColor];
    [backgroundView addSubview:whiteView];
    
    SelectAddressTool *addressView = [[SelectAddressTool alloc] initWithFrame:CGRectMake(0, 0, ScreenWidthMao, 400)];
    [whiteView addSubview:addressView];
    addressView.delegate = self;
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(cancleAction:)];
    [cancleView addGestureRecognizer:tap];
    
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn.frame = CGRectMake(ScreenWidthMao - 80, 0, 80, 55);
    [rightBtn setTitle:@"确定" forState:UIControlStateNormal];
    [rightBtn setTitleColor:ThemeMaoColor forState:UIControlStateNormal];
    rightBtn.titleLabel.font = [UIFont boldSystemFontOfSize:16];
    [rightBtn addTarget:self action:@selector(sureBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [whiteView addSubview:rightBtn];
    
    [UIView animateWithDuration:0.3 animations:^{
        [[HFQCommonTools lastWindow] addSubview:backgroundView];
    }];
}

- (void)selectAddressProvince:(UILabel *)province City:(UILabel *)city District:(UILabel *)district {
    
    if (!province.text.length || [province.text isEqualToString:@"请选择"]) {
        self.nowAddressLabel.text = @"请选择";
        self.provinceCode = @"";
        self.cityCode = @"";
        self.districtCode = @"";
    }else if (!city.text.length || [city.text isEqualToString:@"请选择"]) {
        self.nowAddressLabel.text = [NSString stringWithFormat:@"%@", province.text];
        self.nowAddressLabel.textColor = HexColor(0x333333);
        self.provinceCode = [NSString stringWithFormat:@"%@", province.accessibilityLabel];
        self.cityCode = @"";
        self.districtCode = @"";
    }else if (!district.text.length || [district.text isEqualToString:@"请选择"]) {
        self.nowAddressLabel.text = [NSString stringWithFormat:@"%@ %@", province.text, city.text];
        self.provinceCode = [NSString stringWithFormat:@"%@", province.accessibilityLabel];
        self.cityCode = [NSString stringWithFormat:@"%@", city.accessibilityLabel];
        self.districtCode = @"";
    }else {
        self.nowAddressLabel.text = [NSString stringWithFormat:@"%@ %@ %@", province.text, city.text, district.text];
        self.provinceCode = [NSString stringWithFormat:@"%@", province.accessibilityLabel];
        self.cityCode = [NSString stringWithFormat:@"%@", city.accessibilityLabel];
        self.districtCode = [NSString stringWithFormat:@"%@", district.accessibilityLabel];
    }
    
    if ([self cheakData]) {
        self.tiJiaoBtn.alpha = 1;
        self.tiJiaoBtn.userInteractionEnabled = YES;
    }else {
        self.tiJiaoBtn.alpha = 0.5;
        self.tiJiaoBtn.userInteractionEnabled = NO;
    }
}

- (void)sureBtnAction:(UIButton *)sender{
    
    if (!self.provinceCode.length) {
        [HUD_Mao showCharacterMessage:@"请选择省份"];
        return;
    }else if (!self.cityCode.length) {
        [HUD_Mao showCharacterMessage:@"请选择城市"];
        return;
    }else if (!self.districtCode.length) {
        [HUD_Mao showCharacterMessage:@"请选择区县"];
        return;
    }
    UIView *whiteView = sender.superview;
    UIView *backgroundView = whiteView.superview;
    
    [UIView animateWithDuration:0.3 animations:^{
        backgroundView.alpha = 0;
    } completion:^(BOOL finished) {
        backgroundView.hidden = YES;
        [backgroundView removeFromSuperview];
    }];
}

- (void)cancleAction:(UITapGestureRecognizer *)gesture {
    
    UIView *view = gesture.view;
    UIView *backgroundView = view.superview;
    [UIView animateWithDuration:0.3 animations:^{
        
        backgroundView.alpha = 0;
    } completion:^(BOOL finished) {
        backgroundView.hidden = YES;
        [backgroundView removeFromSuperview];
    }];
}



- (UILabel *)headerLabel {
    
    if (!_headerLabel) {
        _headerLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 0, ScreenWidthMao - 40, 40)];
        _headerLabel.text = @"请确保你本人的信息真实有效";
        _headerLabel.numberOfLines = 2;
        _headerLabel.font = [UIFont systemFontOfSize:12];
        _headerLabel.textColor = HexColor(0x999999);
        [_headerLabel setTextAlignment:NSTextAlignmentLeft];
        _headerLabel.backgroundColor = HexColor(0xF4F4F4);
        
        [self.view addSubview:_headerLabel];
    }
    return _headerLabel;
}


- (UIButton *)tiJiaoBtn {
    
    if (!_tiJiaoBtn) {
        _tiJiaoBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_tiJiaoBtn addTarget:self action:@selector(tiJiaoBtnAction) forControlEvents:UIControlEventTouchUpInside];
        _tiJiaoBtn.alpha = 0.5;
        _tiJiaoBtn.userInteractionEnabled = NO;
        
        [self.view addSubview:_tiJiaoBtn];
    }
    return _tiJiaoBtn;
}

- (MyInfoAddressModel *)addressModel {
    
    if (!_addressModel) {
        _addressModel = [[MyInfoAddressModel alloc] init];
    }
    return _addressModel;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
